package com.jxs.easysecurity.token;

import com.jxs.easysecurity.session.SessionManager;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.logging.Logger;

/**
 * 从{@link HttpServletRequest}中读取访问凭证。
 * 默认会先从头信息{@value tokenHeaderName}中获取凭证，如果找不到再到查询参数{@value tokenQueryParamName}中获取。
 * 你可以使用{@link #setTokenHeaderName(String)}和{@link #setTokenQueryParamName(String)}来设置如何从请求中获取凭证。
 *
 * @author jiangxingshang
 * @since 17/6/20
 */
public class AccessTokenReader {

    private static final Logger log = Logger.getLogger(AccessTokenReader.class.getName());

    private static String tokenQueryParamName = "_token";
    private static String tokenHeaderName = "X-User-Token";

    public static void setTokenQueryParamName(String name) {
        tokenQueryParamName = name;
    }

    public static void setTokenHeaderName(String name) {
        tokenHeaderName = name;
    }

    /**
     * @return 如果没有会返回Null值。
     */
    public static String getAccessToken() {
        HttpServletRequest request = SessionManager.getRequest();
        String token = request.getHeader(tokenHeaderName);
        if(StringUtils.isBlank(token)) {
            token = request.getParameter(tokenQueryParamName);
        }
        if(StringUtils.isNotBlank(token)) {
            return token;
        } else {
            log.info("Access token is empty");
            return null;
        }
    }
}
